package ua.tach.shortl.logic;

import ua.tach.shortl.Renderer;

import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.Texture;

public class Wagon {
	private static final int BASEINDEX = 5;
	public static final float WAGONSIZE = Train.WAGONSIZE;

	// Train dynamic constants
	public static final float BRAKE_DISTANCE = 25.0f;
	public static final float BRAKE_RATE = 0.12f;
	public static final float THROTTLE_RATE = 0.07f;

	private Texture tex;
	private Mesh mesh;
	public RailPosition current;
	public boolean isFree;
	public Train train;

	public Wagon(int type, RailPosition r, Train ow) {
		setWagon(type, r, ow);
	}

	public void setWagon(int type, RailPosition r, Train ow) {
		current = r;
		tex = Renderer.toLoad[BASEINDEX+type].tx;
		mesh = Renderer.toLoad[BASEINDEX+type].m;
		train = ow;
		isFree = false;
	}

	public boolean tick() {
		if(train.movingDirection) {
			current.pos += train.speed;
		} else {
			current.pos -= train.speed;
		}

		//System.out.println ("Tick "+ttype+" pos "+ current.pos + " dir " + movingDirection);
		if (!current.base.isCorrectPos(current)) {
			//System.out.println ("Check sp "+train.speed+" pos "+ current.pos);
			if(current.base.getNextRail(current)) {
				//System.out.println ("Turn!");
				train.reqToTurn = true;
				}
		}

		return current.base.getCoordinate(current);
	}

	public void checkWay () {
		float oldpos = current.pos;
		if(train.movingDirection) {
			current.pos += train.maxSpeed*BRAKE_DISTANCE;
		} else {
			current.pos -= train.maxSpeed*BRAKE_DISTANCE;
		}
		if (!current.base.isFreeWay(current)) {
			//System.out.println ("Check sp "+train.speed+" pos "+ current.pos+" dir "+ train.movingDirection);
			if (train.speed == 0) {
				if ( train.stopCounter < 0 ) {
					train.speed = 0.001f;
					train.movingDirection = !train.movingDirection;
				} else --train.stopCounter;
			} else if (train.speed > 0.0005f) {
				train.speed -= train.maxSpeed*BRAKE_RATE;
			} else {
				train.speed = 0;
				train.stopCounter = 5;
			}
		} else {
			if (train.speed < train.maxSpeed) {
				train.speed += train.maxSpeed*THROTTLE_RATE;
			}
		}
		current.pos = oldpos;
	}

	public void render (GL10 gl) {
		if(current.atDepot) return;
		gl.glEnable(GL10.GL_BLEND);
		tex.bind();
		gl.glPushMatrix();
		gl.glTranslatef(current.renderCoord.x, 0, current.renderCoord.y);
		gl.glRotatef(current.rotate, 0, current.rotate, 0);
		gl.glColor4f(train.owner.x,train.owner.y,train.owner.z,1);
		mesh.render(GL10.GL_TRIANGLES);
		gl.glColor4f(1.f, 1.f, 1.f, 1.f);
		gl.glDisable(GL10.GL_BLEND);
		gl.glPopMatrix();
	}
}
